package com.yc.framework.listener;

import com.rabbitmq.client.Channel;
import com.yc.common.core.domain.model.EmailCaptchaMessage;
import com.yc.common.utils.email.EmailTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Base64;

/**
 * @Author YanChen
 * @Date 2025/4/24 10:51
 **/
@Component
public class EmailCaptchaListener {

    private static final Logger logger = LoggerFactory.getLogger(EmailCaptchaListener.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 处理验证码邮件消息
     *
     * @param message 邮件消息对象
     * @param channel RabbitMQ通道
     * @param deliveryTag 投递标签
     */
    @RabbitListener(queues = "email.captcha.queue")
    public void processEmailMessage(EmailCaptchaMessage message, Channel channel,
                                    @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            logger.info("收到验证码邮件消息，开始处理. 收件人: {}", message.getTo());

            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

            helper.setFrom(from);
            helper.setTo(message.getTo());
            String subject = message.getSubject() != null ? message.getSubject() : "验证码";
            helper.setSubject(subject);

            // 将Base64图片解码
            byte[] imageBytes = Base64.getDecoder().decode(message.getCaptchaImageBase64());

            // 为内嵌图片创建唯一的ContentID（简单明了不带空格和特殊字符）
            String cid = "captcha" + System.currentTimeMillis();

            // 创建HTML内容，使用cid引用图片
            String content = EmailTemplateUtil.createEmailHtmlWithCid(subject, cid);
            helper.setText(content, true);

            // 添加内嵌图片，专注于最大兼容性
            ByteArrayResource imageResource = new ByteArrayResource(imageBytes) {
                @Override
                public String getFilename() {
                    return "captcha.jpg"; // 明确指定文件名
                }
            };
            helper.addInline(cid, imageResource, "image/jpeg");

            // 发送邮件
            mailSender.send(mimeMessage);
            logger.info("验证码邮件发送成功，收件人：{}", message.getTo());

            // 手动确认消息已处理
            channel.basicAck(deliveryTag, false);
        } catch (MessagingException e) {
            logger.error("验证码邮件发送失败", e);
            handleDeliveryError(channel, deliveryTag, e);
        } catch (IOException e) {
            logger.error("RabbitMQ通道操作失败", e);
            try {
                channel.basicReject(deliveryTag, false);
            } catch (IOException ex) {
                logger.error("RabbitMQ拒绝消息失败", ex);
            }
        } catch (Exception e) {
            logger.error("处理验证码邮件消息时发生未知错误", e);
            handleDeliveryError(channel, deliveryTag, e);
        }
    }

    /**
     * 处理投递错误
     */
    private void handleDeliveryError(Channel channel, long deliveryTag, Exception e) {
        try {
            channel.basicReject(deliveryTag, false);
        } catch (IOException ex) {
            logger.error("RabbitMQ拒绝消息失败", ex);
        }
    }
}